import Taro from '@tarojs/taro'
import { iQOOLog } from '@utils/tools'
import IQRequest from '@common/iq-request/request'


// 打开新页面并跳转
function jump(params: { type?: string | number; query?: any; url?: string; WxLog?: {} }) {
    console.log('wxlog', !!params?.WxLog)
    if (!!params?.WxLog) {
        iQOOLog(params?.WxLog, 'trace')
    }
    if (!!!Taro[params.type || 'navigateTo']) console.error('传输正确的跳转类型')
    const paramsStr = handleParams(params.query || {})
    console.log('传输参数---', params)
    if (params.url == '/modules/pages/post-details/index') {
        onGetThreadInfo(params, paramsStr)
    } else if (params?.url?.indexOf('/modules/pages/post-details/index') != -1) {
        const regExp = /\/modules\/pages\/post-details\/index\?threadId=(\d+)/;
        const matchResult = params?.url?.match(regExp);
        const threadId = matchResult?.[1];
        const urlWithoutParams = params?.url?.split('?')[0];
        params.url = urlWithoutParams
        params.query = {}
        params.query.threadId = threadId
        const paramsStr = handleParams(params.query || {})
        onGetThreadInfo(params, paramsStr)
    } else {
        Taro[params.type || 'navigateTo']({
            url: params.url + paramsStr
        })
    }

}

// 返回上一页
function back(outTime = 0) {
    setTimeout(() => {
        Taro.navigateBack({
            delta: 1,
            fail(err) {
                jump({ url: '/pages/index/index', type: 'switchTab' })
            }
        })
    }, outTime);
}
function onGetThreadInfo(info, paramsStr) {
    IQRequest.VIVORequest('v3/thread.detail', {
        threadId: info.query.threadId
    }, { method: 'GET' }).then((response: any) => {
        console.log('jump get thread info', response)
        Taro.setStorageSync('postThreadInfo', response)
        Taro[info.type || 'navigateTo']({
            url: info.url + paramsStr
        })
    })
}
// 参数转换拼接
function handleParams(params) {
    let paramsStr = ''
    if (params && typeof params === 'object') {
        const keys = Object.keys(params) || []
        if (keys && keys.length) {
            keys.forEach((key, index) => {
                // paramsStr =
                if (index === 0) {
                    paramsStr += `?${key}=${params[key]}`
                } else {
                    paramsStr += `&${key}=${params[key]}`
                }
            })
        }
    }
    return paramsStr
}

export default {
    jump, back
}